package com.eclipse.training.swt.helloworld.ui;

import java.util.concurrent.TimeUnit;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;

public class ClientArea extends SashForm {

	private LeftComposite leftComposite;

	public ClientArea(Composite parent, int style) {
		super(parent, style);

		/*
		 * Set the layout
		 */
		setLayout(new GridLayout());
		setLayoutData(new GridData(GridData.FILL_BOTH));

		/*
		 * Create content
		 */
		leftComposite = new LeftComposite(this, SWT.NONE);
		new RightComposite(this, SWT.BORDER);

		/*
		 * Set the weights of the sash form
		 */
		setWeights(new int[] { 2, 1 });
		pack();

		/*
		 * Start a background thread that updates a label
		 */
		startBackgroundThread();
	}

	private void startBackgroundThread() {
		/*
		 * Create and run a user thread
		 */
		Thread t = new Thread(new Runnable() {
			int count = 0;

			@Override
			public void run() {
				while (!isDisposed()) {
					/*
					 * Update the label in a UI thread!
					 */					
					Display.getDefault().asyncExec(new Runnable() {

						@Override
						public void run() {
							if (!isDisposed())
								leftComposite.updateLabel(count++);
						}
					});
					try {
						TimeUnit.MILLISECONDS.sleep(leftComposite
								.getSleepTime());
					} catch (InterruptedException e) {
						// Do Nothing
					}
				}
			}
		});
		t.start();
	}

	public void enableTabs(boolean enabled) {
		leftComposite.getTabFolder().setEnabled(enabled);
	}

}
